import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServerSuperPlus {
    private ServerSocket listenSocket = null;
    public TCPServerSuperPlus(int pork) throws IOException {
        listenSocket = new ServerSocket(pork);
    }
    protected void start() throws IOException {
        System.out.println("服务器上线");
        while (true){
            Socket clientSocket = listenSocket.accept();
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        process(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    private void process(Socket clientSocket) throws IOException, InterruptedException {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            String log = String.format("[%s:%d] 客户端上线",clientSocket.getInetAddress().toString(),
                                               clientSocket.getPort());
            System.out.println(log);
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    log = String.format("[%s:%d] 客户端下线",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    System.out.println(log);
                    break;
                }
                String request = scanner.next();
                String response = responseFun(request);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                log = String.format("[%s:%d],%s,%s",clientSocket.getInetAddress().toString(),
                                         clientSocket.getPort(),request,response);
                System.out.println(log);
                clientSocket.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    protected String responseFun(String request) {
        return request + "嘎嘎";
    }

    public static void main(String[] args) throws IOException {
        TCPServerSuperPlus tcpServerSuperPlus = new TCPServerSuperPlus(9999);
        tcpServerSuperPlus.start();

    }
}
